package com.cyou.weplay.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * SecurityUtils
 *
 * @author zhaomingyu
 */
public class SecurityUtils {

    private static final Logger logger = LoggerFactory.getLogger(SecurityUtils.class);
    private static SecretKey key = null;
    private static final String DEFAULT_SECKEY_K1 = "k1_U2FsdGVkX18zSNO65f3";
    private static final String ALGORITHM = "DES";

    static {
        try {
            String pass = DEFAULT_SECKEY_K1;
            DESKeySpec dks = new DESKeySpec(pass.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            key = keyFactory.generateSecret(dks);
        } catch (Exception ex) {
            logger.error("error init SecurityUtils", ex);
        }
    }

    public static String encrypt(String src) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] result = cipher.doFinal(src.getBytes());
        return Base64.encodeBase64String(result);
    }

    public static String decrypt(String sec) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] result = cipher.doFinal(Base64.decodeBase64(sec));
        return new String(result);
    }

    public static String[] decryptLoginInfo(String secInfo) throws Exception {
        int tagIdx = secInfo.indexOf('^');
        if (tagIdx == -1) {
            return null;
        }
        return decryptLoginInfo(secInfo.substring(0, tagIdx), secInfo.substring(tagIdx + 1));
    }

    public static String[] decryptLoginInfo(String key, String sec) throws Exception {
        String[] info = null;
        try {
            String infoStr = decrypt(sec);
            info = infoStr.split("\\^");
        } catch (Exception e) {
            logger.error("error when decryptLoginInfo", e);
        }
        return info;
    }

    public static String calculateUAuth(String uid) throws Exception {
        return SecurityUtils.encrypt(uid);
    }

    public static String decodeUAuth(String uauth) throws Exception {
        return SecurityUtils.decrypt(uauth);
    }

    public static String calculateUToken(long uid, String udid) {
        return DigestUtils.md5Hex(uid + "^" + udid + "^" + DEFAULT_SECKEY_K1);
    }

    public static void main(String[] args) throws Exception {
        System.out.println(encrypt("356205059490552^1.03.006-25"));
        String[] s = decryptLoginInfo("k1", "k5MVD4cNRf78JjY/Nvchlxs8E5BRbB0KxaHjQ0cuTzk=");
        
    }
}
